<template>
  <div>
    <!-- 搜索栏 -->
    <el-card id="search">
      <el-row>
        <el-col :span="20">
          <el-input v-model="searchModel.name" placeholder="姓名"></el-input>
          <el-input v-model="searchModel.enrollmentYear" placeholder="入学年份"></el-input>
          <el-input v-model="searchModel.faculty" placeholder="学院"></el-input>
          <el-button
            type="primary"
            round
            icon="el-icon-search"
            @click="getUserList"
            >查询</el-button
          >
        </el-col>
        <el-col :span="4" align="right">
          <el-button
            @click="openEditUI(null)"
            type="primary"
            icon="el-icon-plus"
            circle
          ></el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 结果列表 -->
    <el-card>
      <el-table :data="userList" stripe style="width: 100%">
        <el-table-column
          prop="id"
          label="id"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column label="用户状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="statusType(scope.row.status)" effect="dark">
              {{ statusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="200"
          align="center"
        ></el-table-column>
        <el-table-column prop="pic" label="头像" width="100" align="center">
          <template slot-scope="scope">
            <img
              :src="scope.row.pic || defaultAvatar"
              @error="handleError"
              alt="头像"
              style="width: 50px; height: 50px; border-radius: 50%"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="姓名"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="sex"
          label="性别"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="phone"
          label="电话"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="address"
          label="住址"
          width="200"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="studentId"
          label="学号"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="enrollmentYear"
          label="入学年份"
          width="60"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="faculty"
          label="所在学院"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div>
              <el-button
                @click="openEditUI(scope.row.id)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                circle
              ></el-button>
              <el-button
                @click="deleteUser(scope.row)"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                circle
              ></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 用户消息编辑对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      @close="clearForm"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="userForm" ref="userFormRef" :rules="rules">
        <el-form-item
         v-if="userForm.id == null || userForm.id == undefined"
          label="账号"
          prop="username"
          :label-width="formLabelWidth"
        >
          <el-input v-model="userForm.username" autocomplete="off"></el-input>
        </el-form-item>
        
        <el-form-item
          v-if="userForm.id == null || userForm.id == undefined"
          label="用户密码"
          prop="password"
          :label-width="formLabelWidth"
        >
          <el-input v-model="userForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="用户姓名"
          prop="name"
          :label-width="formLabelWidth"
        >
          <el-input v-model="userForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <!-- 测试头像上传 -->
        <el-form-item label="上传图片" :label-width="formLabelWidth">
          <el-upload
            class="upload-demo"
            action="http://localhost:8088/files"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :show-file-list="false"
          >
            <el-button size="small" type="primary">上传图片</el-button>
          </el-upload>
          <img
            v-if="pic"
            :src="pic"
            alt="uploaded image"
            style="width: 100px; height: 100px; margin-top: 10px"
          />
        </el-form-item>

        <el-form-item label="性别" prop="sex" :label-width="formLabelWidth">
          <el-select v-model="userForm.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="用户电话"
          prop="phone"
          :label-width="formLabelWidth"
        >
          <el-input v-model="userForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="用户邮箱"
          prop="email"
          :label-width="formLabelWidth"
        >
          <el-input v-model="userForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="用户住址"
          prop="address"
          :label-width="formLabelWidth"
        >
          <el-input v-model="userForm.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="用户学号"
          prop="studentId"
          :label-width="formLabelWidth"
        >
          <el-input v-model="userForm.studentId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="入学年份"
          prop="enrollmentYear"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-model="userForm.enrollmentYear"
            type="year"
            placeholder="选择入学年份"
            :value-format="'yyyy'"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          label="所在学院"
          prop="faculty"
          :label-width="formLabelWidth"
        >
          <el-input v-model="userForm.faculty" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAndDelete">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userApi from "@/api/userManage";
import { formatDate } from "@/utils/dateFormat";
export default {
  data() {
    return {
      defaultAvatar: require("@/assets/default.jpeg"),
      formLabelWidth: "130px",
      userForm: {
        email: "",
        status: "",
        password: "",
        name: "",
        sex: "",
        phone: "",
        address: "",
        studentId: "",
        enrollmentYear: null,
        faculty: "",
        pic: "",
      },
      newAvatarUrl: "",
      oldAvatarUrl: "",
      dialogFormVisible: false,
      title: "",
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 10,
        enrollmentYear:"",
        name: "",
        faculty: "",
      },
      userList: [],
      pic: "", // 用于显示上传的图片
      formLabelWidth: "100px",
      rules: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            type: "email",
            message: "请输入有效的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 12,
            message: "长度在 5 到 12 个字符",
            trigger: "blur",
          },
        ],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        phone: [{ required: true, message: "请输入电话", trigger: "blur" }],
        address: [{ required: true, message: "请输入住址", trigger: "blur" }],
        studentId: [{ required: true, message: "请输入学号", trigger: "blur" }],
        enrollmentYear: [
          { required: true, message: "请选择入学年份", trigger: "blur" },
        ],
        faculty: [{ required: true, message: "请输入学院", trigger: "blur" }],
      },
    };
  },
  mounted() {
    this.getUserList();
  },
  methods: {
    statusType(status) {
      switch (status) {
        case 1:
          return "success"; // 例如：活跃状态
        case 0:
          return "danger"; // 例如：已冻结状态
        default:
          return "info";
      }
    },
    statusText(status) {
      switch (status) {
        case 1:
          return "活跃";
        case 0:
          return "禁用";
        default:
          return "未知状态";
      }
    },
    handleError(event) {
      event.target.src = this.defaultAvatar;
    },
    deleteUser(user) {
      this.$confirm(`您确认删除用户 ${user.name}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          userApi.deleteUserById(user.id).then((response) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getUserList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    saveUser() {
      this.$refs.userFormRef.validate((valid) => {
        if (valid) {
          // 判断是否需要删除旧头像
          if (
            this.oldAvatarUrl &&
            this.oldAvatarUrl !== this.userForm.pic
          ) {
            console.log("Deleting old avatar:", this.oldAvatarUrl);
            this.deleteOldAvatar(this.oldAvatarUrl); // 删除旧头像
          }
          this.submitUser(); // 提交用户信息
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    submitUser() {
      this.userForm.pic = this.pic; // 存入表单数据中
      // 提交给后台
      userApi.saveUser(this.userForm).then((response) => {
        this.$message({
          message: response.message,
          type: "success",
        });
        // 关闭对话框
        this.dialogFormVisible = false;
        // 刷新表格
        this.getUserList();
      });
    },
    clearForm() {
      this.userForm = {};
      this.newAvatarUrl = ""; // **更改：清空新头像URL**
      this.$refs.userFormRef.clearValidate();
    },
    cancelAndDelete() {
      if (!this.userForm.id && this.newAvatarUrl) {
        // **新增：新增用户且上传了头像的情况下，取消时删除新头像**
        const fileName = this.newAvatarUrl.split("/").pop();
        userApi.deleteImage(fileName).catch((error) => {
          console.error("取消操作时删除新头像失败", error);
        });
      }
      this.dialogFormVisible = false;
      this.clearForm(); // 清除表单数据
    },
    beforeUpload(file) {
      // 你可以在这里添加文件类型和大小的验证
      const isImage = file.type.startsWith("image/");
      if (!isImage) {
        this.$message.error("只能上传图片文件！");
      }
      return isImage;
    },
    handleUploadSuccess(response, file) {
      this.oldAvatarUrl = this.userForm.pic; // 在上传前保存旧头像
      console.log("old");
      console.log(this.oldAvatarUrl);
      console.log(response.data);
      // 更新新头像 URL
      this.pic = response.data;
      this.newAvatarUrl = response.data;
      this.userForm.pic = response.data;
    },
    deleteOldAvatar(oldAvatarUrl) {
      if (oldAvatarUrl) {
        // 检查传入的旧头像 URL
        const fileName = oldAvatarUrl.split("/").pop(); // 使用旧头像的 URL 获取文件名
        userApi
          .deleteImage(fileName)
          .then(() => {
            console.log("Old avatar deleted successfully:", oldAvatarUrl);
          })
          .catch((error) => {
            console.error("删除旧头像失败", error);
          });
      } else {
        console.log("No old avatar to delete.");
      }
    },
    openEditUI(id) {
      if (id == null) {
        this.title = "新增用户";
        this.userForm = {};
        this.pic = "";
        this.newAvatarUrl = "";
      } else {
        this.title = "修改用户";
        userApi.getUserById(id).then((response) => {
          this.userForm = response.data;
          this.pic = response.data.pic;
        });
      }
      this.dialogFormVisible = true;
    },
    handleSizeChange(newSize) {
      this.searchModel.pageSize = newSize;
      this.searchModel.pageNo = 1;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      this.searchModel.pageNo = newPage;
      this.getUserList();
    },
    getUserList() {
      userApi
        .getUserList(this.searchModel)
        .then((response) => {
          this.total = response.data.total;
          this.userList = response.data.list;
        })
        .catch((error) => {
          console.error("获取用户列表失败", error);
        });
    },
    formatDate(row, column, cellValue) {
      return formatDate(cellValue);
    },
  },
};
</script>

<style>
#search .el-input {
  width: 200px;
  margin-right: 10px;
}
.el-dialog .el-input {
  width: 85%;
}
.el-dialog__headerbtn {
  display: none;
}
</style>
